﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RN.ERP.Entity;
using RN.ERP.DAL;
using System.Configuration;
using Fly.FlyCommon;
using Fly.Log;
using RN.ERP.DAL.DAL;


namespace RN.ERP.BLL
{

    public class StoreBLL
    {
         private string _appId = ConfigurationManager.AppSettings["AppID"];

        private StoreContext baseContext;

        private StoreContext dbContext
        {
            get
            {
                return (StoreContext)this.baseContext;
            }
        }

        public StoreBLL()
        {
            this.baseContext = new StoreContext();
        }

        public List<DTO.Storehouse> GetList()
        {
            var query = from a in dbContext.DbStorehouse
                        where a.iStatus == 0
                        select a;

            List<Storehouse> list = query.OrderByDescending(m => m.dCDate).ToList();
            List<DTO.Storehouse> lists = new List<DTO.Storehouse>();
            foreach (Storehouse item in list)
            {
                DTO.Storehouse role = new DTO.Storehouse();
                EntityHelper.ConvertEntity2OtherEntity(item, role);

                string cCUName = T_Sys_UsersDAL.GetNameByUserGuid(item.cCUid.ToString());

                string cUUName = T_Sys_UsersDAL.GetNameByUserGuid(item.cUUid.ToString());


                role.iStatus = item.iStatus == 0 ? "有效" : "无效";
                role.cCUName = cCUName;
                role.CUUName = cUUName;

                lists.Add(role);
            }
            return lists;
        }

        public DTO.Storehouse GetStorehouse(string cSHCode)
        {
            Storehouse m = dbContext.DbStorehouse.SingleOrDefault(mp => mp.cSHCode == cSHCode && mp.iStatus == 0);
            DTO.Storehouse storehouse = new DTO.Storehouse();
            if (m != null)
            {
                EntityHelper.ConvertEntity2OtherEntity<Storehouse, DTO.Storehouse>(m, storehouse);
                storehouse.cCUName = GetNameByUserGuid(m.cCUid.ToString());
                storehouse.CUUName = GetNameByUserGuid(m.cUUid.ToString());
                return storehouse;
            }
            else
            {
                return null;
            }
        }
        public List<DTO.Storehouse> GetList(string cPSHCode)
        {
            var query = from a in dbContext.DbStorehouse
                        where a.cPSHCode == cPSHCode && a.iStatus == 0
                        select a;

            List<Storehouse> list = query.OrderByDescending(m => m.dCDate).ToList();
            List<DTO.Storehouse> lists = new List<DTO.Storehouse>();
            foreach (Storehouse item in list)
            {
                DTO.Storehouse role = new DTO.Storehouse();
                EntityHelper.ConvertEntity2OtherEntity(item, role);

                string cCUName = T_Sys_UsersDAL.GetNameByUserGuid(item.cCUid.ToString());

                string cUUName = T_Sys_UsersDAL.GetNameByUserGuid(item.cUUid.ToString());
                

                role.iStatus = item.iStatus == 0 ? "有效" : "无效";
                role.cCUName = cCUName;
                role.CUUName = cUUName;

                lists.Add(role);
            }
            return lists;
        }


        public DTO.OperationResult DeleteStorehouse(string id)
        {
            DTO.OperationResult result = new DTO.OperationResult() { Result = false };

            Storehouse mProperty = dbContext.DbStorehouse.SingleOrDefault(mp => mp.cSHCode == id && mp.iStatus == 0);
            if (mProperty != null)
            {
                mProperty.iStatus = 1;
                try
                {
                    if (dbContext.SaveChanges() > 0)
                    {
                        result.Result = true;
                        result.Message = "仓储删除成功！";
                        UserLogManager.Log(new User_Log()
                        {
                            AppId = _appId,
                            Content = "删除仓储",
                            FunctionId = FunctionId.MaterialProperty.ToString(),
                            FunctionType = FunctionType.Delete.ToString(),
                            IsrtDate = DateTime.Now,
                            IsrtUser = mProperty.cCUid.ToString()
                        });
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "仓储删除失败：" + ex.Message;
                }
            }
            else
            {
                result.Message = "未找到需要删除的仓储！";
            }

            return result;
        }



        public string GetCSHCode()
        {
            return GetCode("B_Storehouse", "cSHCode",3);
        }

        /// <summary>
        /// 根据表名，字段名及最大长度生成编号。
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="columnName"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        internal string GetCode(string tableName, string columnName, int maxLength)
        {
            string strSql = string.Format("select top 1 {0} from {1} order by id desc", columnName, tableName);
            string result = dbContext.Database.SqlQuery<string>(strSql).FirstOrDefault();
            if (string.IsNullOrEmpty(result))
            {
                return "1".PadLeft(maxLength, '0');
            }
            else
            {
                int index = 1;
                int.TryParse(result, out index);
                return (index + 1).ToString().PadLeft(maxLength, '0');
            }
        }

        public string GetNameByUserGuid(string userGuid)
        {
            return T_Sys_UsersDAL.GetNameByUserGuid(userGuid);
        }

        public DTO.OperationResult AddStorehouse(DTO.Storehouse property)
        {
            DTO.OperationResult result = new DTO.OperationResult() { Result = false };

            Storehouse Storehouse = new Storehouse();
            EntityHelper.ConvertEntity2OtherEntity<DTO.Storehouse, Storehouse>(property, Storehouse);
            Storehouse.dCDate = DateTime.Now;
            Storehouse.cSHCode = new StoreBLL().GetCode("B_Storehouse", "cSHCode", 3);
            try
            {
                Storehouse = dbContext.DbStorehouse.Add(Storehouse);
                if (dbContext.SaveChanges() > 0)
                {
                    result.Result = true;
                    result.Message = "仓储添加成功！";
                    UserLogManager.Log(new User_Log()
                    {
                        AppId = _appId,
                        Content = "添加仓储",
                        FunctionId = FunctionId.MaterialClass.ToString(),
                        FunctionType = FunctionType.Add.ToString(),
                        IsrtDate = DateTime.Now,
                        IsrtUser = Storehouse.cCUid.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                result.Message = "仓储添加失败：" + ex.Message;
            }

            return result;
        }

        public DTO.OperationResult EditStorehouse(DTO.Storehouse property)
        {
            DTO.OperationResult result = new DTO.OperationResult() { Result = false };

            Storehouse Storehouse = dbContext.DbStorehouse.SingleOrDefault(mp => mp.Id == property.Id && mp.iStatus == 0);
            if (Storehouse == null)
            {
                result.Message = "无此仓储信息！";
                return result;
            }
            Storehouse.cMemo = property.cMemo;
            //Storehouse.cMCCode = property.cMCCode;
            Storehouse.cSHName = property.cSHName;
            Storehouse.cSHCode = property.cSHCode;
            //Storehouse.dCDate = property.dCDate;
            //Storehouse.cCUID = property.cCUID;
            Storehouse.cUUid = property.cUUid;
            Storehouse.dUDate = DateTime.Now;
            Storehouse.iStatus = int.Parse(property.iStatus);
            if (dbContext.SaveChanges() > 0)
            {
                result.Result = true;
                result.Message = "仓储修改成功！";
                UserLogManager.Log(new User_Log()
                {
                    AppId = _appId,
                    Content = "修改仓储",
                    FunctionId = FunctionId.MaterialClass.ToString(),
                    FunctionType = FunctionType.Edit.ToString(),
                    IsrtDate = DateTime.Now,
                    IsrtUser = Storehouse.cCUid.ToString()
                });
            }

            return result;
        }

       
    }
}
